import time
import sys
import os
import errno

from twisted.web import server
from twisted.internet import reactor
from twisted.python import threadable

from root import Root

args = sys.argv
pid_filename = 'server.pid'


def startServer():
    if os.access(pid_filename, os.R_OK):
        try:
            pid_content = open(pid_filename).read()
            pid = int(pid_content)
            os.kill(pid, 9)
        except OSError, e:
            if e[0] == errno.ESRCH:
                os.unlink(pid_filename)
            else:
                raise
        else:
            print 'Server is running?'

    pid = os.fork()
    if not pid:
        pid_file = file(pid_filename, 'w', 128)
        pid = os.getpid()
        pid_file.write(str(pid) + '\n')
        pid_file.close()

        threadable.init()
        reactor.listenTCP(8000, server.Site(Root()))
        reactor.run()

def stopServer():
    pid_file = file(pid_filename, 'r', 128)
    pid_content = pid_file.readline().strip()
    pid = int(pid_content)
    pid_file.close()
    os.kill(pid, 9)
    os.unlink(pid_filename)

if args[1] == 'start':
    startServer()
elif args[1] == 'stop':
    stopServer()
elif args[1] == 'restart':
    stopServer()
    time.sleep(1)
    startServer()

